package com.liliudong.template.biz.service.sys.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.liliudong.template.biz.mapper.sys.SysRoleDeptMapper;
import com.liliudong.template.biz.service.sys.SysRoleDeptService;
import com.liliudong.template.common.constant.ExMessage;
import com.liliudong.template.common.entity.sys.SysRoleDept;
import com.liliudong.template.common.exception.BizException;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

import static com.liliudong.template.common.entity.sys.table.SysRoleDeptTableDef.SYS_ROLE_DEPT;

/**
 * SysRoleDeptService
 *
 * @author liudo
 * @version 1.0
 * @project template-backend
 * @date 2024/7/31 14:35:55
 */
@Service
public class SysRoleDeptServiceImpl extends ServiceImpl<SysRoleDeptMapper, SysRoleDept> implements SysRoleDeptService {

    @Override
    public void saveBatchWithRoleId(Long roleId, List<Long> deptIds) {
        if (CollectionUtil.isEmpty(deptIds)) {
            return;
        }
        if (Objects.isNull(roleId)) {
            throw new BizException(ExMessage.ROLE_EMPTY);
        }
        List<SysRoleDept> roleDeptList = deptIds.stream()
                .map(deptId -> {
                    SysRoleDept roleDept = new SysRoleDept();
                    roleDept.setRoleId(roleId);
                    roleDept.setDeptId(deptId);
                    return roleDept;
                }).collect(Collectors.toList());
        saveBatch(roleDeptList);
    }

    @Override
    public void removeByRoleId(Long roleId) {
        if (Objects.isNull(roleId)) {
            throw new BizException(ExMessage.ROLE_EMPTY);
        }
        remove(SYS_ROLE_DEPT.ROLE_ID.eq(roleId));
    }

    @Override
    public Set<Long> listDeptIdsByRoleId(Long roleId) {
        return queryChain()
                .select(SYS_ROLE_DEPT.DEPT_ID)
                .where(SYS_ROLE_DEPT.ROLE_ID.eq(roleId))
                .list()
                .stream()
                .map(SysRoleDept::getDeptId)
                .collect(Collectors.toSet());
    }

    @Override
    public long countByDeptId(Long deptId) {
        return count(SYS_ROLE_DEPT.DEPT_ID.eq(deptId));
    }
}
